package com.oscar;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.oscar.dao.EmployeeDAO;
import com.oscar.dao.StoreInforDAO;
import com.oscar.helper.IntuireHelper;
import com.oscar.helper.SettingsHelper;
import com.oscar.helper.StoreHelper;

public class LoginFragment extends Fragment {

	public static final String LOG_TAG = "LoginFragment";
	public static final String ARG_PLANET_NUMBER = "planet_number";

	public LoginFragment() {
	}

	private Button login;
	private TextView id, code;
	private StoreInforDAO storeinfoDAO = new StoreInforDAO();
	private EmployeeDAO employeeDAO = new EmployeeDAO();
	private EditText edtusername;
	private EditText edtpassword;
	private CheckBox chbSaveUserPass;
	private static final String SPF_NAME = "settings"; // <--- Add this
	private static final String USERNAME = "username"; // <--- To save username
	private static final String PASSWORD = "password";
	private Boolean isFirstLoading = true;

	ProgressDialog ringProgressDialog = null;
	private boolean flag_ringprogress = false;

	@Override
	public void onPause() {
		super.onPause();
		IntuireHelper.isStoped = true;
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_login, container,
				false);
		login = (Button) rootView.findViewById(R.id.login_btn_login);
		edtusername = (EditText) rootView.findViewById(R.id.login_edt_email);
		edtpassword = (EditText) rootView.findViewById(R.id.login_edt_password);
		chbSaveUserPass = (CheckBox) rootView
				.findViewById(R.id.chb_SaveUserPass);
		if (isFirstLoading == true) {
			isFirstLoading = false;
			initData();
		}
		login.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				/*Intent i = new Intent(getActivity(), SplashScreen.class);
				startActivity(i);*/
				Boolean check = chbSaveUserPass.isChecked();
				new LoginTask().execute(edtusername.getText().toString(), edtpassword.getText().toString(),check.toString());
			}
		});
		return rootView;
	}

	private void initData() {
		getActivity().setTitle("LOGIN");
		getActivity().getActionBar().setHomeButtonEnabled(false);
		SharedPreferences loginPreferences = getActivity()
				.getSharedPreferences(SPF_NAME, Context.MODE_PRIVATE);
		edtusername.setText(loginPreferences.getString(USERNAME, ""));
		edtpassword.setText(loginPreferences.getString(PASSWORD, ""));
		if (loginPreferences.getString(USERNAME, "").equals("") == false) {
			chbSaveUserPass.setChecked(true);
		}
	}

	private class LoginTask extends AsyncTask<String, Void, Boolean> {
		private final ProgressDialog dialog = new ProgressDialog(getActivity(),
				ProgressDialog.THEME_HOLO_DARK);

		@SuppressWarnings("static-access")
		@Override
		protected void onPreExecute() {

			dialog.setCancelable(true);
			dialog.setMessage(getText(R.string.login_loading));
			dialog.setIndeterminate(true);
			dialog.show();
			super.onPreExecute();
		}

		protected Boolean doInBackground(String... strs) {
			String username = (String) strs[0];
			String pass = (String) strs[1];
			String s_check = (String) strs[2];
			Boolean check = Boolean.parseBoolean(s_check);
			try {
				boolean checkLogin = storeinfoDAO.checkLoginStoreInfor(
						username, pass);
				if (checkLogin == true) {
					StoreHelper.IdStore = username;
					StoreHelper.NameStore = storeinfoDAO.getStoreWithID(
							username).getStoreName();
					SettingsHelper.setUserNameStored(getActivity(), username);
					Log.i(LOG_TAG, "login susscess");
					if (check == true) {
						SharedPreferences loginPreferences = getActivity()
								.getSharedPreferences(SPF_NAME,
										Context.MODE_PRIVATE);
						loginPreferences.edit().putString(USERNAME, username)
								.putString(PASSWORD, pass).commit();
						((MainActivity)getActivity()).setLogin(true);
	    				((MainActivity)getActivity()).setCode("abc");
	    				((MainActivity)getActivity()).setId("123");
					} else {
						SharedPreferences loginPreferences = getActivity()
								.getSharedPreferences(SPF_NAME,
										Context.MODE_PRIVATE);
						loginPreferences.edit().clear().commit();
					}
					return true;
				} else {
					Log.i(LOG_TAG, "login fail id and pass");
					return false;
				}
			} catch (Exception ex) {
				Log.i(LOG_TAG, "login fail exception");
				Log.e(LOG_TAG, ex.getMessage());
				return false;
			}
		}

		protected void onPostExecute(Boolean result) {
			Log.i(LOG_TAG, "Finish login");
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			if (result == true) {
				((MainActivity) getActivity()).changeFragment(
						new ReportFragment(), "");
				((MainActivity) getActivity()).loginRow
						.setBackgroundColor(Color.parseColor("#91BEF7"));
				((MainActivity) getActivity()).loginId.setText("Login as "
						+ StoreHelper.IdStore);

				((MainActivity) getActivity()).getActionBar()
						.setDisplayHomeAsUpEnabled(true);
				((MainActivity) getActivity()).getActionBar()
						.setHomeButtonEnabled(true);
			} else {
				Toast.makeText(getActivity(),
						getResources().getString(R.string.login_error), Toast.LENGTH_LONG)
						.show();
			}
		}
	}


}
